package com.sskj.cndragon.ui.activity;


import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.AwardNoticeBean;
import com.sskj.cndragon.bean.TurntableBean;
import com.sskj.cndragon.http.HttpConfig;
import com.sskj.cndragon.presenter.TurntableActivityPresenter;
import com.sskj.cndragon.turntable.RotateListener;
import com.sskj.cndragon.turntable.WheelSurfView;
import com.sskj.cndragon.view.ToolBarLayout;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.util.TipUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class TurntableActivity extends BaseActivity<TurntableActivityPresenter> {
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.tv_times)
    TextView tvTimes;
    @BindView(R.id.btn_get_quan)
    Button btnGetQuan;
    //    @BindView(R.id.tv_wanshan)
//    TextView tvWanshan;
    @BindView(R.id.iv_turntable)
    WheelSurfView rotateView;

    private int times;

    private TurntableBean winTurntableBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_turntable;
    }

    @Override
    public TurntableActivityPresenter getPresenter() {
        return new TurntableActivityPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar.setLeftButtonOnClickListener(view -> finish());
        toolbar.setRightButtonOnClickListener(view -> WinningRecordActivity.start(this));
        ClickUtil.click(300, btnGetQuan, () -> GetQuanActivity.start(this));
//        ClickUtil.click(300, tvWanshan, () -> AddressManagerActivity.start(this));

        rotateView.setRotateListener(new RotateListener() {
            @Override
            public void rotateEnd(int position, String desc) {
//                ToastUtil.showShort(desc);
                if (winTurntableBean == null) {
                    return;
                }
                if (winTurntableBean.getId().equals("6")) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appHenyihan));
                    return;
                }
                TipUtil.turntableTip(TurntableActivity.this, NumberUtil.keepNoZero(winTurntableBean.getPrizeNum()), winTurntableBean.getPrizeName(), new TipUtil.OnTipSure() {
                    @Override
                    public void onSure() {
                        WinningRecordActivity.start(TurntableActivity.this);
                    }
                });
            }

            @Override
            public void rotating(ValueAnimator valueAnimator) {

            }

            @Override
            public void retateBefore(ImageView goImg) {
                if (times < 1) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appChoujiangquanbuzu));
                    return;
                }
                mPresenter.chouJiang(SPUtil.get(SPConfig.ID, ""));
            }
        });


        tvNotice.setFactory(() -> {
            TextView textView = new TextView(this);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.white));
            return textView;
        });


    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.getTicketsCount(SPUtil.get(SPConfig.ID, ""));
        mPresenter.getTableDatas();
        mPresenter.getAwardList();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mPresenter.getTicketsCount(SPUtil.get(SPConfig.ID, ""));
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, TurntableActivity.class);
        context.startActivity(intent);
    }

    @SuppressLint("CheckResult")
    public void updataTables(List<TurntableBean> turntableBeans) {
        if (turntableBeans == null || turntableBeans.size() < 1) {
            return;
        }
        Integer[] colors = new Integer[turntableBeans.size()];
        Observable.fromIterable(turntableBeans)
                .map(turntableBean -> {
                    HashMap<String, Bitmap> hashMap = new HashMap<>();
//                    Bitmap bitmap = null;
//                    if (isEmpty(turntableBean.getPrizeImgUrl())) {
//                        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.iphone);
//                    } else {
//                        URL imageurl = null;
//                        try {
//                            imageurl = new URL(HttpConfig.BASE_URL + turntableBean.getPrizeImgUrl());
//                        } catch (MalformedURLException e) {
//                            e.printStackTrace();
//                        }
//                        try {
//
//                            HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
//                            conn.setDoInput(true);
//                            conn.connect();
//                            InputStream is = conn.getInputStream();
//                            bitmap = BitmapFactory.decodeStream(is);
//                            is.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    Glide.with(TurntableActivity.this).asBitmap()
//                            .load(isEmpty(turntableBean.getPrizeNum()) ?
//                                    R.mipmap.iphone : HttpConfig.BASE_URL + turntableBean.getPrizeNum())
//                            .into(new SimpleTarget<Bitmap>() {
//                                @Override
//                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                                    hashMap.put(NumberUtil.keepNoZero(turntableBean.getPrizeNum()) + turntableBean.getPrizeName(), resource);
//                                }
//                            });
                    hashMap.put(NumberUtil.keepNoZero(turntableBean.getPrizeNum()) + turntableBean.getPrizeName()
                            , BitmapFactory.decodeResource(getResources(), R.mipmap.iphone));
                    return hashMap;
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HashMap<String, Bitmap>>() {
                    List<String> deses = new ArrayList<>();
                    List<Bitmap> mIcons = new ArrayList<>();

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HashMap<String, Bitmap> stringBitmapHashMap) {
                        Iterator iter = stringBitmapHashMap.keySet().iterator();
                        while (iter.hasNext()) {
                            String next = (String) iter.next();
                            deses.add(next);
                            mIcons.add(stringBitmapHashMap.get(next));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        deses.add("再来一次");
                        mIcons.add(BitmapFactory.decodeResource(getResources(), R.mipmap.iphone));
                        //主动旋转一下图片
                        mIcons = WheelSurfView.rotateBitmaps(mIcons);

                        //获取第三个视图
                        WheelSurfView.Builder build = new WheelSurfView.Builder()
                                .setmColors(colors)
                                .setmTextColor(Color.WHITE)
                                .setmDeses(deses.toArray(new String[deses.size()]))
                                .setmIcons(mIcons)
                                .setmType(1)
                                .setmTypeNum(turntableBeans.size() + 1)
                                .build();
                        rotateView.setConfig(build);

                    }
                });

//        for (int i = 0; i < turntableBeans.size(); i++) {
//            deses.add(NumberUtil.keepNoZero(turntableBeans.get(i).getPrizeNum()) + turntableBeans.get(i).getPrizeName());
//            if (isEmpty(turntableBeans.get(i).getPrizeNum())) {
//                mIcons.add(BitmapFactory.decodeResource(getResources(), R.mipmap.iphone));
//            } else {
//                mIcons.add(returnBitMap(HttpConfig.BASE_URL + turntableBeans.get(i).getPrizeNum()));
//            }
//        }
//
//        deses.add("再来一次");
//        mIcons.add(BitmapFactory.decodeResource(getResources(), R.mipmap.iphone));
//        //主动旋转一下图片
//        mIcons = WheelSurfView.rotateBitmaps(mIcons);
//
//        //获取第三个视图
//        WheelSurfView.Builder build = new WheelSurfView.Builder()
//                .setmColors(colors)
//                .setmTextColor(Color.WHITE)
//                .setmDeses(deses.toArray(new String[deses.size()]))
//                .setmIcons(mIcons)
//                .setmType(1)
//                .setmTypeNum(turntableBeans.size() + 1)
//                .build();
//        rotateView.setConfig(build);
    }

    public void getTicketsOK(String data) {
        if (isEmpty(data)) {
            return;
        }
        times = Integer.valueOf(data);
        tvTimes.setText(data);
    }

    public void chouJiangOK(TurntableBean turntableBean) {
        if (turntableBean == null) {
            return;
        }
        mPresenter.getTicketsCount(SPUtil.get(SPConfig.ID, ""));
        winTurntableBean = turntableBean;
        rotateView.startRotate(Integer.valueOf(turntableBean.getId()));
    }

    Bitmap bitmap;

    public Bitmap returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {

                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }

    private Disposable noticeDispo;
    private AwardNoticeBean awardNoticeBean;

    public void updataAwardList(List<AwardNoticeBean> data) {
        if (data == null) {
            return;
        }
        if (tvNotice != null) {
            if (data.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                awardNoticeBean = data.get((int) (i % data.size()));
                                tvNotice.setText(TimeFormatUtil.formatH(awardNoticeBean.getCreateTime()) + " "
                                        + awardNoticeBean.getUsername() + " 转盘获得 "
                                        + awardNoticeBean.getPrizeName()
                                        + "x" + NumberUtil.keepNoZero(awardNoticeBean.getPrizeNum()));
                            }
                        }, System.out::println);
            }
        }
    }
}
